<template>
  <div class="login">
    <div class="pic-box">
      <div class="inner-pic">
        <progressive-img :placeholder="bigPic" :origin="bigPic" />
      </div>
      <div class="pic-bg">
        <progressive-img :placeholder="smallPic" :origin="smallPic" />
      </div>
    </div>
    <div class="right-box">
      <div class="mask-box">
        <el-form ref="loginRef" :model="loginForm" :rules="loginRules" class="login-form">
          <div style="width: 100%; text-align: center; font-size: 20px;">
            管理系统
          </div>
          
          <ul class="swicth-btns">
            <li class="btn" :class="{ 'active-btn-right': activeBtn === 0 }" @click="activeBtn = 0">密码登录</li>
            <li class="btn" :class="{ 'active-btn-left': activeBtn === 1 }" @click="activeBtn = 1">验证码登录</li>
          </ul>

          <template v-if="activeBtn === 0">
            <el-form-item prop="username">
              <el-input v-model="loginForm.username" type="text" size="large" auto-complete="off" placeholder="账号">
                <template #prefix><svg-icon icon-class="user" class="el-input__icon input-icon" /></template>
              </el-input>
            </el-form-item>
            <el-form-item prop="password">
              <el-input v-model="loginForm.password" type="password" size="large" auto-complete="off" placeholder="密码"
                @keyup.enter="handleLogin">
                <template #prefix><svg-icon icon-class="password" class="el-input__icon input-icon" /></template>
              </el-input>
            </el-form-item>
          </template>
          <template v-else>
            <el-form-item prop="username">
              <el-input v-model="loginForm.username" type="text" size="large" auto-complete="off" placeholder="账号">
                <template #prefix><svg-icon icon-class="user" class="el-input__icon input-icon" /></template>
              </el-input>
            </el-form-item>
            <el-form-item prop="smscode">
              <el-input v-model="loginForm.smscode" type="text" size="large" auto-complete="off" placeholder="验证码"
                @keyup.enter="handleLogin">
                <template #prefix><svg-icon icon-class="validCode" class="el-input__icon input-icon" /></template>
                <template #append>
                  <el-button type="primary" style="color: #ffffff" :disabled="isSendCode"
                    :style="{ background: isSendCode ? '#2b2f3a50' : '#2b2f3a' }" size="large" @click="sendSmsCode">{{
                      !isSendCode ? '发送验证码' : sendTime + '秒后重试' }}</el-button>
                </template>
              </el-input>
            </el-form-item>
          </template>

          <div style="clear: both;">
            <el-checkbox v-model="loginForm.rememberMe" style="margin:0px 0px 25px 0px">记住密码</el-checkbox>
            <div style="float: right">
              <router-link class="link-type" :to="'/register'">立即注册</router-link>
            </div>
          </div>

          <el-form-item style="width:100%;">
            <el-button :loading="loading" size="large" type="primary" style="width:100%;" @click.prevent="handleLogin">
              <span v-if="!loading">登 录</span>
              <span v-else>登 录 中...</span>
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>

    <!--  底部  -->
    <div class="el-login-footer">
      <span>Copyright © 2025.</span>
    </div>
  </div>
</template>

<script setup>
import Cookies from "js-cookie"
import { encrypt, decrypt } from "@/utils/jsencrypt"
import useUserStore from '@/store/modules/user'
import ProgressiveImg from "@/components/ProgressiveImg/index"

import { getCode } from '@/api/login'
const userStore = useUserStore()
const route = useRoute()
const router = useRouter()
const { proxy } = getCurrentInstance()

const smallPic = ref('https://yheyan.oss-cn-beijing.aliyuncs.com/images/login_bg_icon.png')
const bigPic = ref('https://yheyan.oss-cn-beijing.aliyuncs.com/images/login_bg_pic.png')

const activeBtn = ref(0)
const activeBtnLeft = computed(() => activeBtn.value === 1 ? '175px' : '0px')
const loginForm = ref({
  username: "admin",
  password: "111111",
  smscode: null,
  rememberMe: false
});

const loginRules = {
  username: [{ required: true, trigger: "blur", message: "请输入您的账号" }],
  password: [{ required: true, trigger: "blur", message: "请输入您的密码" }],
  code: [{ required: true, trigger: "change", message: "请输入验证码" }],
  smscode: [{ required: true, trigger: "change", message: "请输入验证码" }]
};

const isSendCode = ref(false)
const sendTime = ref(60)
const timer = ref(null)

const loading = ref(false);
const redirect = ref(undefined);

watch(route, (newRoute) => {
  redirect.value = newRoute.query && newRoute.query.redirect;
}, { immediate: true });

// 发送验证码
const sendSmsCode = () => {
  if (!loginForm.value.username) return proxy.$message.error('请输入手机号')
  const data = {
    username: loginForm.value.username
  }

  getCode(data).then(res => {
    isSendCode.value = true

    timer.value = setInterval(() => {
      sendTime.value--
      if (sendTime.value <= 0) {
        clearInterval(timer.value)
        isSendCode.value = false
        sendTime.value = 60
      }
    }, 1000)
  })
}

function handleLogin() {
  proxy.$refs.loginRef.validate(valid => {
    if (valid) {
      loading.value = true;
      // 勾选了需要记住密码设置在 cookie 中设置记住用户名和密码
      if (loginForm.value.rememberMe) {
        Cookies.set("username", loginForm.value.username, { expires: 30 })
        Cookies.set("password", encrypt(loginForm.value.password), { expires: 30 })
        Cookies.set("rememberMe", loginForm.value.rememberMe, { expires: 30 })
      } else {
        // 否则移除
        Cookies.remove("username")
        Cookies.remove("password")
        Cookies.remove("rememberMe")
      }
      if (activeBtn.value === 0) {
        // 调用action的登录方法
        userStore.login(loginForm.value).then(() => {
          const query = route.query;
          const otherQueryParams = Object.keys(query).reduce((acc, cur) => {
            if (cur !== "redirect") {
              acc[cur] = query[cur]
            }
            return acc
          }, {})
          router.push({ path: redirect.value || "/", query: otherQueryParams })
        }).catch(() => {
          loading.value = false
        })
      } else {
        // 调用action的登录方法
        userStore.loginByCode(loginForm.value).then(() => {
          const query = route.query;
          const otherQueryParams = Object.keys(query).reduce((acc, cur) => {
            if (cur !== "redirect") {
              acc[cur] = query[cur]
            }
            return acc
          }, {})
          router.push({ path: redirect.value || "/", query: otherQueryParams })
        }).catch(() => {
          loading.value = false
        })
      }
    }
  })
}

function getCookie() {
  const username = Cookies.get("username")
  const password = Cookies.get("password")
  const rememberMe = Cookies.get("rememberMe")
  loginForm.value = {
    username: username === undefined ? loginForm.value.username : username,
    password: password === undefined ? loginForm.value.password : decrypt(password),
    rememberMe: rememberMe === undefined ? false : Boolean(rememberMe)
  }
}

getCookie()
</script>

<style lang='scss' scoped>
.login {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 100%;
  background: #ffffff;
  width: 100%;
  min-width: 1366px;

  .pic-box {
    width: 590px;
    height: 100%;
    position: relative;

    .inner-pic {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      z-index: 10;
    }

    .pic-bg {
      position: absolute;
      top: 50%;
      left: 50%;
      z-index: 100;
      width: 428px;
      height: 428px;
      transform: translate(-50%, -50%);
    }
  }

  .right-box {
    width: calc(100% - 590px);
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    position: relative;

    .logo {
      width: 160px;
      height: 120px;
    }
  }
}

.title {
  margin: 0px auto 30px auto;
  text-align: center;
  color: #333333;
  position: relative;
  z-index: 100;
}

.mask-box {
  border-radius: 6px;
  width: 400px;
  padding: 25px 25px 5px 25px;
  position: relative;

  &::before {
    content: "";
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    z-index: 10;

    background: rgba(255, 255, 255, 0.8);
    box-shadow: 0 8px 32px 0 rgba(31, 38, 135, 0.3);
    backdrop-filter: blur(20px);
    -webkit-backdrop-filter: blur(20px);
    border-radius: 10px;
    border: 1px solid rgba(255, 255, 255, 0.18);
  }
}

.login-form {
  z-index: 100;
  position: relative;

  .swicth-btns {
    width: 350px;
    height: 40px;
    border-radius: 4px;
    list-style: none;
    padding: 0;
    margin: 20px auto 40px;
    display: flex;
    background: #aaaaaa;
    justify-content: space-between;
    align-items: center;
    position: relative;

    &::after {
      content: "";
      position: absolute;
      top: 1px;
      left: 1px;
      width: calc(50% - 2px);
      height: 38px;
      background: #ffffff;
      transform: translateX(v-bind('activeBtnLeft'));
      transition: transform 0.3s ease-in;
      border-radius: 4px;
      z-index: inherit;
    }

    .btn {
      cursor: pointer;
      width: calc(50% - 2px);
      height: 38px;
      line-height: 38px;
      margin: 1px;
      text-align: center;
      color: #ffffff;
      font-size: 14px;
      border-radius: 4px;
      position: relative;
      z-index: 100;

      &:hover {
        color: #2b2f3a;
      }
    }

    .active-btn-right {
      color: #2b2f3a;
    }

    .active-btn-left {
      color: #2b2f3a;
    }
  }

  .el-input {
    position: relative;
    z-index: 100;
    height: 40px;

    input {
      height: 40px;
    }
  }

  .input-icon {
    height: 39px;
    width: 14px;
    margin-left: 0px;
  }
}

.login-tip {
  font-size: 13px;
  text-align: center;
  color: #bfbfbf;
}

.el-login-footer {
  height: 40px;
  line-height: 40px;
  position: fixed;
  bottom: 0;
  width: 100%;
  text-align: center;
  color: #fff;
  font-family: Arial;
  font-size: 12px;
  letter-spacing: 1px;
}

.login-code-img {
  height: 40px;
  padding-left: 12px;
}
</style>
